<?php

namespace app\admin\app\model;

use plugin\admin\app\model\Base;

/**
 * @property integer $id 主键(主键)
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property integer $category_id 分类
 * @property integer $admin_id 管理员
 * @property string $filename 文件名
 * @property string $path 素材
 * @property integer $status 状态
 */
class Material extends Base
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'wa_material';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';


    public function getLink()
    {
        if ($this->filename) {
            $pattern = '/https?:\/\/[^\s]+/';
            preg_match_all($pattern, $this->filename, $matches);
            return current($matches[0]);
        } else {
            return '';
        }
    }


    public function getPathAttribute($value)
    {
        return $value && strpos($value, 'http') === false ? config('qiniu.domain') . $value : $value;
    }

    public function getCoverAttribute($value)
    {
        return $value && strpos($value, 'http') === false ? config('qiniu.domain') . $value : $value;
    }

    protected static function booted()
    {
//        static::deleting(function ($model) {
//            $qiniu = new Qiniu();
//            $domain = config('qiniu.domain');
//            if ($model->path) {
//                $qiniu->delete(str_replace($domain, '', $model->path));
//            }
//            if ($model->cover) {
//                $qiniu->delete(str_replace($domain, '', $model->cover));
//            }
//        });
    }
}
